package com.geese.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;

public abstract class MD5Util {
	
	public static Logger logger = LoggerFactory.getLogger(MD5Util.class);
	
	private static final String ALGORITHM = "MD5";
	private static final Charset CHARSET = Charsets.UTF_8;
	private static final String EMPTY_STRING = "";

	public static String encrypt(String input) {
		return encrypt(input, CHARSET);
		
	}

	private static String encrypt(String input, Charset charsetName) {
		try {
			MessageDigest md5 = MessageDigest.getInstance(ALGORITHM);
			byte md5Bytes[] = md5.digest(input.getBytes(charsetName));
			return byteToHex(md5Bytes);
		} catch (NoSuchAlgorithmException e) {
			logger.error("当前不支持该算法类型： algorithm=" + ALGORITHM);
		}
		return EMPTY_STRING;
	}

	public static String encryptFile(String path) {
		try {
			return encrypt(new FileInputStream(new File(path)));
		} catch (FileNotFoundException e) {
			logger.error("文件找不到： path=" + path);
		}
		return EMPTY_STRING;
    }


	public static String encrypt(InputStream inputStream) {
		try {
			byte[] data = IOUtils.toByteArray(inputStream);
			MessageDigest md = MessageDigest.getInstance(ALGORITHM);
			md.update(data, 0, data.length);
			return byteToHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			logger.error("当前不支持该算法类型： algorithm=" + ALGORITHM);
		} catch (IOException e) {
		} 
		return EMPTY_STRING;
	}
	
	private static String byteToHex(byte[] b) {
		StringBuilder strb = new StringBuilder();
		for (int n = 0; n < b.length; n++) {
			String stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				strb.append("0");
			}
			strb.append(stmp);
		}
		return strb.toString();
	}

}
